﻿using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Api_Dto;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Model;
using Service.Socket;
using TcpService;

namespace JHService.Api
{
    [Route("api/[action]")]
    public class DeviceApi : ControllerBase
    {
        private Socket_RSServer _socketRsServer = ServiceLocator.Instance.GetService<Socket_RSServer>();
        [HttpGet]
        public List<int> GetParametersList(int deviceid)
        {

            var paramIdsDataHelp = ServiceLocator.Instance.GetService<ParamIdsDataHelp>();
            for (int i = 0; i < 1; i++)
            {
                var res = _socketRsServer.ReadParametersList(deviceid);
                Thread.Sleep(1000);
                if (!paramIdsDataHelp.Success)
                {
                    continue;
                }
                else
                {
                    return paramIdsDataHelp.ParamIdsDataModel;

                }
            }

            return null;
        }
        [HttpGet]
        public async Task<ApiMessageEntity> GetCallParam(int deviceid)
        {
            var msg = new ApiMessageEntity();
            var parametersList = GetParametersList(deviceid);

            if (deviceid <= 0 || parametersList == null)
            {
                return msg;
            }
            // var receiveParam = ServiceLocator.Instance.GetService<ReceiveParamHelp>();
            //for (int i = 0; i < 1; i++)
            //{
           await _socketRsServer.ReadCallParamsAsync(deviceid, parametersList);
            Thread.Sleep(2000);
            var receiveParam = Socket_RSServer._receiveParamHelp;
            if (receiveParam.Success)
            {
                msg.requstresult = ApiReturnState.Success;
                msg.data = receiveParam.ParamDataModel;
            }
            return msg;
        }
        [HttpGet]
        public async Task<ApiMessageEntity> WriteParameters(int deviceid, int paramid, string paramval)
        {
            var msg = new ApiMessageEntity();
            var writeParamHelp = ServiceLocator.Instance.GetService<WriteParamHelp>();
            await _socketRsServer.WriteParametersAsync(deviceid, paramid, paramval);
            Thread.Sleep(2000);
            if (writeParamHelp.Success)
            {
                msg.requstresult = ApiReturnState.Success;
            }
            return msg;
        }
    }
}